<template>
  <PageContainer>
    <view class="container">
      <Header :title="isReset ? '重新发送' : '新建消息'" />
      <view class="bgf br-8 mx-15 my-10">
        <view class="disFlxJS pl-15 pr-5 py-12 borderBottom">
          <view class="fz-15 flexShrink pr-10 _isRequired">消息类型</view>
          <picker
            class="px-10"
            mode="multiSelector"
            @change="onChange"
            @columnchange="onColumnchange"
            range-key="name"
            :range="msgTypeOptions"
            :value="msgTypeValue"
            :disabled="isReset || isAppoint"
          >
            <PickerValue
              :valueText="checkedMsgTypeObj?.name"
              placeholder="请选择"
              :icon="isReset || isAppoint ? '' : '&#xe6c7;'"
            />
          </picker>
        </view>
      </view>

      <view class="bgf br-8 mx-15 my-10" v-if="checkedMsgTypeObj?.associatedObjects">
        <view class="disFlxJS pl-15 pr-5 py-12">
          <view class="fz-15 flexShrink pr-10 _isRequired">关联内容</view>
          <view>
            <text v-if="isReset" class="pr-10">
              {{ objectText }}
            </text>
            <text v-else-if="!relevanceOptions.length" class="pr-10 fz-14" style="color: #aaabab">
              此类型暂无关联内容
            </text>
            <FormSelector
              v-else
              v-model="addForm.objectId"
              icon="&#xe6c7;"
              :localdata="relevanceOptions"
              :border="false"
              @change="relevanceChange"
            />
          </view>
        </view>
      </view>

      <!-- 消息类型自定义消息时显示 -->
      <view
        class="bgf br-8 mx-15 my-10"
        v-if="checkedMsgTypeObj?.customType === CustomTypeEnum.YES"
      >
        <view class="disFlxJS pl-15 pr-5 py-12">
          <view class="fz-15 flexShrink pr-10 _isRequired">自定义页面</view>
          <view class="px-10" @click="goEditor">
            <PickerValue
              :valueText="addForm.customPageId ? '已设置' : ''"
              placeholder="请输入自定义页面内容"
              icon="&#xe6c7;"
            />
          </view>
        </view>
      </view>

      <view class="bgf br-8 mx-15 my-10">
        <view class="disFlxJS px-15 linh-44">
          <view class="fz-15 flexShrink pr-10 _isRequired">消息标题</view>
          <view style="flex: 1; padding-left: 20rpx">
            <input
              v-model="addForm.title"
              style="text-align: right"
              placeholder-style="color: #AAABAB;"
              placeholder="请输入消息标题"
            />
          </view>
        </view>
      </view>

      <view class="bgf br-8 mx-15 my-10">
        <view class="linh-48 fz-15 px-15 _isRequired">选择发送方式</view>
        <view class="disFlxJS linh-44 px-15 borderBottom">
          <view class="disFlxAC">
            <text class="ali-icon fz-18" style="color: #07c160">&#xe602;</text>
            <text class="pl-8">微信公众号</text>
          </view>
          <view @click="showToast(!wxTemplateOptions.length)">
            <FormSwitch
              v-model="wxSwitch"
              :disabled="
                !wxTemplateOptions.length || checkedMsgTypeObj?.customType === CustomTypeEnum.YES
              "
            />
          </view>
        </view>
        <template v-if="wxSwitch">
          <view class="disFlxJS pl-15 pr-5 py-12">
            <view style="width: 200rpx" class="flexShrink">消息模板</view>
            <view>
              <FormSelector
                v-model="addForm.wechatTemplateId"
                icon="&#xe6c7;"
                :localdata="wxTemplateOptions"
                :border="false"
              />
            </view>
          </view>
          <view class="disFlx pa-15">
            <view style="width: 200rpx" class="flexShrink">消息内容</view>
            <view class="contentBox">
              <text space="nbsp">{{ wxTemplateContent }}</text>
            </view>
          </view>
        </template>

        <view
          v-if="checkedMsgTypeObj?.customType !== CustomTypeEnum.YES"
          class="disFlxJS linh-44 px-15 borderBottom"
        >
          <view class="smsBox disFlxAC" @click="openResidue">
            <text class="ali-icon fz-16" style="color: #2878ff">&#xe601;</text>
            <text class="pl-8">手机短信</text>
            <view class="msmResidue">?</view>
          </view>
          <view @click="showToast(!smsTemplateOptions.length)">
            <FormSwitch v-model="smsSwitch" :disabled="!smsTemplateOptions.length" />
          </view>
        </view>
        <template v-if="smsSwitch">
          <view class="disFlxJS pl-15 pr-5 py-12">
            <view style="width: 200rpx" class="flexShrink">消息模板</view>
            <view>
              <FormSelector
                v-model="addForm.smsTemplateId"
                icon="&#xe6c7;"
                :localdata="smsTemplateOptions"
                :border="false"
              />
            </view>
          </view>
          <view class="disFlx pa-15">
            <view style="width: 200rpx" class="flexShrink">消息内容</view>
            <view class="contentBox">
              <text space="nbsp">{{ smsTemplateContent }}</text>
            </view>
          </view>
        </template>
      </view>

      <view class="bgf br-8 mx-15 my-10">
        <view class="disFlxJS linh-50 pl-15 pr-5">
          <view class="fz-15 _isRequired">选择接收人</view>
          <PickerValue v-if="isAppoint" placeholder="已指定接收人" icon="" />
          <view v-else @click="goSelectUser">
            <PickerValue placeholder="添加接收人" icon="&#xe6c7;" />
          </view>
        </view>
        <view class="disFlxAC linh-50 px-15 flexEnd">
          <view class="pr-10 fz-12">
            已选 {{ checkedUserList.length + '/' + totalNumber.personNumber }}
          </view>
          <TButton
            text="查看已选名单"
            custom-class="br-12 linh-22 fz-12"
            :custom-style="{ height: '48rpx', color: '#2878FF', border: 'solid 1px #2878FF' }"
            @click="goSelectedUser"
          />
        </view>
      </view>

      <TButtonGroup position="fixed" :styles="{ backgroundColor: '#FFF' }">
        <TButton class="gutter-btn" type="primary" text="立即发送" @click="confirm" />
      </TButtonGroup>

      <ShowModal
        v-model="successShow"
        title="消息发送成功"
        content="发送结果请从发送记录列表查看"
        :showCancel="false"
        @confirm="goBack"
      ></ShowModal>

      <ShowModal
        v-model="residueShow"
        title=""
        cancel-text="联系充值"
        confirm-text="知道了"
        @close="makePhoneCall"
      >
        <template #content>
          <view class="px-30" style="text-align: center">
            您的手机短信余量为：{{ smsSurplus }}条，超出短信余量将无法发送。
          </view>
        </template>
      </ShowModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* addMessage 新建消息 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import FormSelector from '@/components/Form/components/FormSelector.vue';
  import PickerValue from '@/components/Form/components/PickerValue.vue';
  import type { Localdata } from '@/components/Form/types';
  import { reactive, ref, unref, computed } from 'vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import FormSwitch from '@/components/Form/components/FormSwitch.vue';
  import {
    getMessageTypeList,
    getSMSTemplatePlaceholderVo,
    getSMSTemplate,
    getWXTemplate,
    getMemberStatistics,
    createdMessage,
    getSmsFindBalance,
    getTemplateTypeById,
    getMemberList,
    getTypeMessageTemplate,
  } from '@/api/admin';
  import type { MsgTypeData, CreateMsgData } from '@/api/admin/types';
  import { CustomTypeEnum, SendTypeEnum } from '@/enums/admin';
  import { navigateBack, navigateTo, onLoad } from '@/router';
  import { useAdminStoreWithOut } from '@/store/modules/admin';
  import { Toast } from '@/utils';
  import ShowModal from '@/components/ShowModal/index.vue';

  const useAdmin = useAdminStoreWithOut();
  const isReset = ref(false); // 是否为重新发送，重新发送禁止选用消息类型和关联对象
  const isAppoint = ref(false); // 是否为指定发送, 指定发送禁止选用消息类型和禁止更换接收人
  onLoad((op) => {
    // useAdmin.currentMsgDetails 重新发送页面处传入整个消息对象
    // 其它页面跳转,指定发送,则只需要传入 op.userIds && op.typeId
    if (op.userIds) {
      op.typeId ? (isAppoint.value = true) : (isReset.value = true);

      addForm.smsTemplateTypeId = op.typeId ?? (useAdmin.currentMsgDetails?.typeId as number); // 消息类型
      addForm.objectId = useAdmin.currentMsgDetails?.associationObjectId; // 关联内容
      addForm.title = useAdmin.currentMsgDetails?.messageTitle ?? ''; // 标题

      switchReturn(); // 发送方式回显

      // 选中的消息类型对象回显
      getTemplateTypeById(addForm.smsTemplateTypeId).then((_r: MsgTypeData) => {
        checkedMsgTypeObj.value = _r;
        // 查询关联内容
        getMsgRelevance(unref(checkedMsgTypeObj).associatedObjects ?? undefined);

        // 选中人员回显, 后端用户数据不满足，通过用户ID重查
        getMemberList({
          current: 1,
          size: op.userIds.length,
          userIds: op.userIds,
          objectId: addForm.objectId,
          dataSource: unref(checkedMsgTypeObj)?.dataSource ?? 'userList',
        }).then((_r) => {
          useAdmin.checkedUserList = _r.records;
        });
        // 获取对应类型的人员统计
        getMemberStatistics({
          objectId: addForm.objectId,
          userIds: unref(isAppoint) ? op.userIds.join(',') : undefined,
          dataSource: unref(checkedMsgTypeObj)?.dataSource ?? 'userList',
        }).then((_r) => {
          useAdmin.totalNumber = _r;
        });
      });

      // 获取自定页面内容的ID
      addForm.customPageId = useAdmin.currentMsgDetails?.customPageId;
      getTypeMessageTemplate({
        messageChannelList: useAdmin.currentMsgDetails?.messageChannelList,
      }).then((_r) => {
        const wxObj = _r.find((v: any) => v.messageChannel === SendTypeEnum.WECHAT);
        addForm.customPageId = wxObj ? wxObj?.customPageId : undefined;
      });
      // 查询对应类型的短信模板
      getMsgSMSTemplate(addForm.smsTemplateTypeId);
      // 查询对应类型的微信模板
      getMsgWXTemplate(addForm.smsTemplateTypeId);
    } else {
      // 获取消息类型列表
      getMessageTypeList({ dataSource: 'userList' }).then((_r: MsgTypeData[]) => {
        oldMsgTypeOptions.value = _r;
        msgTypeOptions.value = [
          unref(oldMsgTypeOptions),
          unref(oldMsgTypeOptions)[0]?.nodeList ?? [],
        ];
      });
      // 获取人员统计
      getMemberStatistics({ dataSource: 'userList' }).then((_r) => {
        useAdmin.totalNumber = _r;
      });
      // 新建消息
      useAdmin.checkedUserList = [];
    }

    // 获取短信余量
    getSmsFindBalance().then((_r) => {
      smsSurplus.value = _r;
    });
  });

  // 已选择的用户列表
  const checkedUserList = computed(() => {
    return useAdmin.checkedUserList;
  });
  // 总用户数和总公司数
  const totalNumber = computed(() => {
    return useAdmin.totalNumber;
  });
  const smsSurplus = ref(0);

  // 消息类型多列选择
  const oldMsgTypeOptions = ref<MsgTypeData[]>([]); // 接口初始数据
  const msgTypeOptions = ref<Array<MsgTypeData[]>>([]); // 级联选择器数据
  const msgTypeValue = ref<number[]>([]); // 级联选择器选中下标
  const checkedMsgTypeObj = ref({} as MsgTypeData); // 当前选中消息类型对象-最后一级为维度

  const onColumnchange = (e: any) => {
    const { column, value } = e.detail;
    if (column === 0) {
      msgTypeOptions.value[1] = unref(oldMsgTypeOptions)[value]?.nodeList ?? [];
    }
  };
  const onChange = (e: any) => {
    msgTypeValue.value = e.detail.value;
    let currentObj = unref(oldMsgTypeOptions)[unref(msgTypeValue)[0]];

    if (currentObj?.nodeList) {
      if (!unref(msgTypeValue)[1]) {
        msgTypeValue.value[1] = 0;
      }
      currentObj = currentObj?.nodeList[unref(msgTypeValue)[1]];
    }

    if (currentObj.customType === CustomTypeEnum.YES) {
      // 自定义类型
      smsSwitch.value = false; // 不显示短信
      wxSwitch.value = true; // 默认打开微信发送
    }
    checkedMsgTypeObj.value = currentObj;

    // 查询关联内容
    getMsgRelevance(currentObj?.associatedObjects ?? undefined);
    // 查询对应类型的短信模板
    getMsgSMSTemplate(currentObj.id);
    // 查询对应类型的微信模板
    getMsgWXTemplate(currentObj.id);
  };

  // 消息关联内容选择
  const relevanceOptions = ref<Localdata[]>([]);
  const objectText = ref<string>();
  const getMsgRelevance = (type: string | undefined) => {
    if (type) {
      getSMSTemplatePlaceholderVo(type).then((_r) => {
        relevanceOptions.value = _r.map((v: { id: number; title: string; type: string }) => {
          return {
            value: v.id,
            text: v.title,
          };
        });
        // 重新发送不允许切换关联内容
        if (!unref(isReset)) {
          // 默认选中第一个关联内容
          addForm.objectId = _r.length ? (unref(relevanceOptions)[0].value as number) : undefined;
          // 默认赋值关联内容名称给标题
          addForm.title = _r.length ? (unref(relevanceOptions)[0].text as string) : '';
        } else {
          const obj = unref(relevanceOptions).find((v) => v.value === addForm.objectId);
          if (obj) {
            objectText.value = obj.text;
          } else {
            addForm.objectId = undefined;
          }
        }
      });
    } else {
      relevanceOptions.value = [];
      addForm.objectId = undefined;
      if (!unref(isReset)) {
        if (unref(checkedMsgTypeObj)?.customType === CustomTypeEnum.YES) {
          addForm.title = '';
        } else {
          // 没有关联内容名称,则将消息内容名称赋值给标题
          addForm.title = unref(checkedMsgTypeObj)?.name ?? addForm.title;
        }
      }
    }
  };
  const relevanceChange = (val: string | number) => {
    addForm.title = unref(relevanceOptions).find((v) => v.value === val)?.text ?? '';
  };

  // 发送方式开关
  const smsSwitch = ref(false);
  const wxSwitch = ref(false);
  // 发送方式回显
  const switchReturn = () => {
    const _sendTypes = ref<string[]>([]);
    if (useAdmin.currentMsgDetails?.messageChannelList) {
      useAdmin.currentMsgDetails?.messageChannelList.forEach((v) => {
        if (v.messageChannel === SendTypeEnum.SMS) {
          addForm.smsTemplateId = v.templateId; // 短信消息模板
        } else if (v.messageChannel === SendTypeEnum.WECHAT) {
          addForm.wechatTemplateId = v.templateId; // 微信消息模板
        }
        _sendTypes.value.push(v.messageChannel); // 发送方式
      });
    }

    // 开关回显
    if (unref(_sendTypes).length) {
      smsSwitch.value = unref(_sendTypes).includes(SendTypeEnum.SMS);
      wxSwitch.value = unref(_sendTypes).includes(SendTypeEnum.WECHAT);
    } else {
      smsSwitch.value = unref(isAppoint);
      wxSwitch.value = unref(isAppoint);
    }
  };

  // 短信模板 -根据选中的消息类型的id查询
  interface TemplateData extends Localdata {
    content: string;
  }
  const smsTemplateOptions = ref<TemplateData[]>([]);
  const getMsgSMSTemplate = (id: number) => {
    getSMSTemplate(id).then((_r) => {
      smsTemplateOptions.value = _r.map((v: any) => {
        return {
          value: v.id,
          text: v.name,
          content: v.smsZhContent,
        };
      });
      // 默认赋值第一个
      if (!unref(isReset)) {
        if (unref(smsTemplateOptions).length) {
          addForm.smsTemplateId = unref(smsTemplateOptions)[0].value as number;
          smsSwitch.value = true;
        } else {
          smsSwitch.value = false;
        }
      }
    });
  };
  const smsTemplateContent = computed(() => {
    if (addForm.smsTemplateId) {
      return unref(smsTemplateOptions).find((v) => v.value === addForm.smsTemplateId)?.content;
    } else {
      return '';
    }
  });
  // 微信模板 -根据选中的消息类型的id查询
  const wxTemplateOptions = ref<TemplateData[]>([]);
  const getMsgWXTemplate = (id: number) => {
    getWXTemplate(id).then((_r) => {
      wxTemplateOptions.value = _r.map((v: any) => {
        return {
          value: v.sceneCode,
          text: v.sceneName,
          content: v.displayContent,
        };
      });
      // 默认赋值第一个
      if (!unref(isReset)) {
        if (unref(wxTemplateOptions).length) {
          addForm.wechatTemplateId = unref(wxTemplateOptions)[0].value as number;
          wxSwitch.value = true;
        } else {
          wxSwitch.value = false;
        }
      }
    });
  };
  const wxTemplateContent = computed(() => {
    if (addForm.wechatTemplateId) {
      return unref(wxTemplateOptions).find((v) => v.value === addForm.wechatTemplateId)?.content;
    } else {
      return '';
    }
  });

  // 新建消息接口所需对象
  const addForm = reactive<CreateMsgData>({
    smsTemplateTypeId: 1, // 消息类型ID
    objectId: undefined, // 关联对象ID，消息类型对象存在associatedObjects字段才需传入
    customPageId: undefined, // 自定义页面内容 目前限制2000字节
    title: '', // 消息标题
    sendTypes: [], // 消息类型 sms:短信，wechat微信，最少传入一种方式
    smsTemplateId: undefined, // 短信模板ID， sendTypes数组存在短信需传入
    wechatTemplateId: undefined, // 微信消息模板ID，sendTypes数组存在微信需传入
    userIds: [],
  });

  // 立即发送
  const successShow = ref(false);
  const confirm = () => {
    if (formInspect()) {
      addForm.smsTemplateTypeId = unref(checkedMsgTypeObj).id;
      unref(smsSwitch) && addForm.sendTypes.push(SendTypeEnum.SMS);
      unref(wxSwitch) && addForm.sendTypes.push(SendTypeEnum.WECHAT);
      addForm.userIds = unref(checkedUserList).map((v) => v.userId);

      createdMessage(addForm).then(() => {
        successShow.value = true;
        useAdmin.setIsResetList(true);
      });
    }
  };

  // 只有重新发送，选择人员才会出现为活动人员
  // 跳转去选择人员页面
  const goSelectUser = function () {
    if (unref(isReset) && unref(checkedMsgTypeObj)?.associatedObjects && !addForm.objectId) {
      Toast('关联内容已不存在');
      return;
    }
    navigateTo({
      name: 'selectUserList',
      options: { dataSource: unref(checkedMsgTypeObj)?.dataSource, objectId: addForm.objectId },
    });
  };
  // 跳转去查看已选人员
  const goSelectedUser = function () {
    if (unref(isReset) && unref(checkedMsgTypeObj)?.associatedObjects && !addForm.objectId) {
      Toast('关联内容已不存在');
      return;
    }
    navigateTo({
      name: 'selectedUserList',
      options: {
        dataSource: unref(checkedMsgTypeObj)?.dataSource,
        objectId: addForm.objectId,
        disabled: true,
      },
    });
  };
  // 查看短信剩余条数
  const residueShow = ref(false);
  const openResidue = () => {
    residueShow.value = true;
  };
  const makePhoneCall = () => {
    uni.makePhoneCall({ phoneNumber: '18188616477' });
  };

  const goBack = function () {
    navigateBack();
  };

  const goEditor = function () {
    navigateTo({
      name: 'h5RichTextEditor',
      options: {
        id: addForm.customPageId,
        callback: (text, id) => {
          console.log(text, id);
          addForm.customPageId = id;
        },
      },
    });
  };

  // 表单必填检验
  const formInspect = () => {
    if (!unref(checkedMsgTypeObj)?.id) {
      Toast('请选择消息类型');
      return false;
    } else if (
      unref(checkedMsgTypeObj)?.customType === CustomTypeEnum.YES &&
      !addForm.customPageId
    ) {
      Toast('请输入自定义页面内容');
    } else if (unref(checkedMsgTypeObj)?.associatedObjects && !addForm.objectId) {
      Toast(unref(isReset) ? '关联内容已不存在' : '请选择关联内容');
      return false;
    } else if (!addForm.title) {
      Toast('请输入消息标题');
      return false;
    } else if (!unref(smsSwitch) && !unref(wxSwitch)) {
      Toast('请选择发送方式');
      return false;
    } else if (unref(smsSwitch) && unref(checkedUserList).length > unref(smsSurplus)) {
      // 选择了短信发送,并且短信余量不足,提示用户
      openResidue();
      return false;
    } else if (!addForm.smsTemplateId && !addForm.wechatTemplateId) {
      Toast('请选择消息模板');
      return false;
    } else if (!unref(checkedUserList).length) {
      Toast('请选择接收人');
      return false;
    } else {
      return true;
    }
  };

  const showToast = (show: boolean) => {
    if (!unref(checkedMsgTypeObj).id) {
      Toast('请选择消息类型');
    } else if (show) {
      Toast('暂无模板');
    }
  };
</script>

<style lang="scss" scoped>
  .container {
    font-size: 28rpx;
    .flexShrink {
      flex-shrink: 0;
    }
    .contentBox {
      background-color: #f5f5f5;
      border-radius: 8rpx;
      padding: 16rpx;
      flex: 1;
    }
    .smsBox {
      position: relative;
      .msmResidue {
        width: 32rpx;
        height: 32rpx;
        border-radius: 50%;
        background-color: #ccccc8;
        color: #fff;
        text-align: center;
        line-height: 32rpx;
        position: absolute;
        top: 30rpx;
        right: -52rpx;
        font-size: 20rpx;
      }
    }
  }
</style>
